
function encodeFormData(data) {
    if (!data) return ''; // Always return a string
    if(typeof data==='string')return data;
    var pairs = []; // To hold name=value pairs

    for (var name in data) {
        // For each name

        if (!data.hasOwnProperty(name)) continue; // Skip inherited
        if (typeof data[name] === 'function') continue; // Skip methods
        var value = data[name];
        // value==undefined同时包含了undefined和null的判断
        value = (value == undefined ? '' : value).toString(); // Value as string
        name = encodeURIComponent(name); // Encode name
        value = encodeURIComponent(value); // Encode value
        pairs.push(name + '=' + value); // Remember name=value pair
    }

    return pairs.join('&').replace(/%20/g, '+'); // Return joined pairs separated with &
}

var cookie_obj = {};

var public_options = {
    timeout : 12*1000,
	withCredentials:true,
    ____proxy: {
        host: '127.0.0.1',
        port: 8888
    },
    auth: {
        username: 'CIJDreact',
        password: 'CIJDreact'
    },
    transformRequest: [function (data, headers) {
        var cookie_arr = [];
        for(var name in cookie_obj){
            var value = cookie_obj[name];
            cookie_arr.push(name+'='+value);
        }
        headers.Cookie = cookie_arr;
        headers.Accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,\*\/*;q=0.8';
        headers.Connection = 'keep-alive';
        headers['Accept-Language'] = 'zh-CN,zh;q=0.8';
        headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36';


        // Do whatever you want to transform the data

        return encodeFormData(data);
    }]
};

function add_public_options(prev_options){
    if((!prev_options) || (typeof prev_options!=='object')){
        prev_options = {};
    }
    var result_options = {};

	for(var k in public_options){
		result_options[k] = public_options[k];
	}
	for(var k in prev_options){
		result_options[k] = prev_options[k];
	}

	return result_options;
}

function save_cookies(response) {
    if(!response)return;
    if(response&&response.headers){
        //console.log('response.headers :\n ' +JSON.stringify(response.headers));// Set-Cookie
        var setCookieArr = response.headers['set-cookie'];

        if(setCookieArr&&setCookieArr.push&&setCookieArr.length){
            for(var i=0; i<setCookieArr.length; i++){
                var itm = setCookieArr[i];
                if((typeof itm==='string') && (itm.match(/.+\=.+\;/))){
                    var a1 = itm.split(';');
                    var c = itm.split(';')[0].split('=');
                    var name = c[0];
                    var value = c[1];
                    cookie_obj[name] = value;

                }
            }
        }
    }
}

module.exports = {
    add_public_options:add_public_options,
    save_cookies:save_cookies
};